<template>
  <div class="about-page">
    <h1>饮食计划制定</h1>
    
    <div class="diet-plans-container">
      <ul v-if="dietPlans.length > 0">
        <li v-for="(plan, index) in dietPlans" :key="plan.plan_id" class="diet-item" :class="{ 'even': index % 2 === 1 }">
          <p><strong>早餐:</strong> 
            <span v-for="(item, i) in plan.breakfast" :key="i">
              {{ item.食物 }} ({{ item.量 }})
              <span v-if="i !== plan.breakfast.length - 1">,</span>
            </span>
          </p>
          <p><strong>午餐:</strong> 
            <span v-for="(item, i) in plan.lunch" :key="i">
              {{ item.食物 }} ({{ item.量 }})
              <span v-if="i !== plan.lunch.length - 1">,</span>
            </span>
          </p>
          <p><strong>晚餐:</strong> 
            <span v-for="(item, i) in plan.dinner" :key="i">
              {{ item.食物 }} ({{ item.量 }})
              <span v-if="i !== plan.dinner.length - 1">,</span>
            </span>
          </p>
          <p><strong>状态:</strong> {{ plan.status }}</p>
        </li>
      </ul>
      <div v-else>
        <p>您还没有饮食计划哦~</p>
      </div>
    </div>
    
    <!-- 添加区域移至列表下方 -->
    <div class="add-plan-container">
      <input v-model="newBreakfast" placeholder="请输入早餐（如：苹果 200克）" />
      <input v-model="newLunch" placeholder="请输入午餐（如：鸡胸肉 150克）" />
      <input v-model="newDinner" placeholder="请输入晚餐（如：米饭 100克）" />
      <button @click="addDietPlan">添加饮食计划</button>
    </div>
  </div>
</template>

<script setup>
import axios from 'axios';
import { ref, onMounted } from 'vue';
import { useUserStore } from '@/stores/counter';

const userStore = useUserStore();
const dietPlans = ref([]);
const loading = ref(false);
const newBreakfast = ref('');
const newLunch = ref('');
const newDinner = ref('');

// 获取当前用户的饮食计划
const fetchUserDietPlans = async () => {
  try {
    const user_id = userStore.userId;
    if (!user_id) {
      console.error('用户未登录，无法获取饮食计划');
      alert('请先登录');
      return;
    }
    
    // 修改接口路径为 diet_plan/all
    const response = await axios.get('http://localhost:8080/MDMS0214_war/diet_plan/all');
    if (response.status === 200) {
      const filteredPlans = response.data
        .filter(plan => plan.user_id === user_id) // 注意接口返回字段为 user_id
        .map(plan => {
          // 解析 plan_content 为 JSON 对象
          const planContent = JSON.parse(plan.plan_content);
          
          return {
            ...plan,
            // 解构早餐/午餐/晚餐数据
            breakfast: planContent.早餐 || [],
            lunch: planContent.午餐 || [],
            dinner: planContent.晚餐 || []
          };
        });
      
      dietPlans.value = filteredPlans;
    } else {
      console.error('获取饮食计划失败，状态码:', response.status);
      alert('获取饮食计划失败，请稍后重试');
    }
  } catch (error) {
    console.error('获取饮食计划失败:', error);
    alert('获取饮食计划失败，请稍后重试');
  }
};

const addDietPlan = async () => {
  try {
    const user_id = userStore.userId;
    if (!user_id) {
      console.error('用户未登录，无法添加饮食计划');
      alert('请先登录');
      return;
    }
    
    // 解析用户输入的早餐/午餐/晚餐格式（假设格式为：食物 量）
    const parseFoodItem = (str) => {
      const parts = str.trim().split(/\s+/);
      if (parts.length < 2) return null;
      return { 食物: parts.slice(0, -1).join(' '), 量: parts[parts.length - 1] };
    };
    
    const breakfastItems = newBreakfast.value.split(',').map(parseFoodItem).filter(item => item);
    const lunchItems = newLunch.value.split(',').map(parseFoodItem).filter(item => item);
    const dinnerItems = newDinner.value.split(',').map(parseFoodItem).filter(item => item);
    
    if (!breakfastItems.length || !lunchItems.length || !dinnerItems.length) {
      alert('请按格式输入（如：苹果 200克）');
      return;
    }
    
    const planContent = JSON.stringify({
      早餐: breakfastItems,
      午餐: lunchItems,
      晚餐: dinnerItems
    });
    
    // 修改接口路径为 diet_plan/add，并调整字段名（user_id 而非 user_Id）
    const response = await axios.post('http://localhost:8080/MDMS0214_war/diet_plan/add', {
      plan_id: null, // 假设后端自动生成主键
      user_id: user_id, // 注意字段名是 user_id
      nutritionist_id: 2, // 假设默认营养师ID为2，需根据实际业务调整
      plan_content: planContent,
      status: "待审核",
      created_at: Date.now() // 后端可能自动处理时间，可省略
    });
    
    if (response.status === 200) {
      await fetchUserDietPlans();
      newBreakfast.value = '';
      newLunch.value = '';
      newDinner.value = '';
    } else {
      console.error('添加饮食计划失败，状态码:', response.status);
      alert('添加饮食计划失败，请稍后重试');
    }
  } catch (error) {
    console.error('添加饮食计划失败:', error);
    alert('添加饮食计划失败，请稍后重试');
  }
};

onMounted(async () => {
  loading.value = true;
  await fetchUserDietPlans();
  loading.value = false;
});
</script>

<style scoped>
/* 全局样式重置，让不同浏览器表现一致 */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}

.about-page {
    font-family: 'Roboto', sans-serif;
    padding: 20px;
    display: flex;
    flex-direction: column;
    align-items: center;
}

h1 {
    font-size: 32px;
    color: #1a1a1a;
    margin-bottom: 30px;
    text-align: center;
}

/* 保持原始添加区域样式不变，仅调整位置 */
.add-plan-container {
    display: flex;
    flex-direction: column;
    align-items: center;
    width: 100%;
    max-width: 900px;
    margin-top: 50px;
}

.add-plan-container input {
    padding: 14px 20px;
    border: 2px solid #ccc;
    border-radius: 20px;
    font-size: 16px;
    width: 100%;
    max-width: 300px;
    margin-bottom: 15px;
    transition: border-color 0.3s ease;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.add-plan-container input:focus {
    outline: none;
    border-color: #009688;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.add-plan-container button {
    padding: 14px 30px;
    background: linear-gradient(45deg, #00b09b, #96c93d);
    color: white;
    border: none;
    border-radius: 20px;
    font-size: 16px;
    cursor: pointer;
    transition: background 0.3s ease;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.add-plan-container button:hover {
    background: linear-gradient(45deg, #96c93d, #00b09b);
    box-shadow: 0 6px 12px rgba(0, 0, 0, 0.15);
}

/* 优化饮食计划区域布局 - 一排最多三个卡片 */
.diet-plans-container {
    width: 100%;
    max-width: 1200px; /* 增加最大宽度以容纳三个卡片 */
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); /* 一排最多三个卡片 */
    gap: 16px; /* 减小间距 */
}

/* 重置列表样式 */
.diet-plans-container ul {
    list-style: none;
    margin: 0;
    padding: 0;
    display: contents;
}

/* 调整卡片大小和样式 */
.diet-item {
    background-color: white;
    border-radius: 16px; /* 减小圆角半径 */
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.08); /* 减小阴影 */
    padding: 16px; /* 减小内边距 */
    transition: all 0.3s ease;
    aspect-ratio: 5/4; /* 调整卡片比例 */
}

.diet-item p {
    margin-bottom: 8px;
    font-size: 17px; /* 原15px，增大2px */
    line-height: 1.4; /* 适当调整行高使阅读更舒适 */
    color: #444;
}

.diet-item strong {
    color: #222;
    font-weight: 600;
    font-size: 18px; /* 新增，比普通文字大1px */
}

.diet-item.even {
    box-shadow: 0 5px 15px rgba(0, 0, 0, 0.1);
}

.diet-item:hover {
    transform: translateY(-4px) scale(1.01); /* 减小悬停效果 */
    box-shadow: 0 6px 18px rgba(0, 0, 0, 0.12);
}

.diet-plans-container div {
    grid-column: 1 / -1;
    font-size: 16px;
    color: #666;
    text-align: center;
    padding: 30px;
    border: 2px dashed #ccc;
    border-radius: 25px;
}
</style>